<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.userName" class="list-input" placeholder="搜索用户名称" @input="handleSearchInput"
               @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.userName" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>
        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">登录地址</text>
            <uni-easyinput v-model="queryParams.ipaddr" placeholder="请输入登录地址" :clearable="true"/>
          </view>
        </view>
        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
    </view>

    <!-- 列表 -->
    <view class="list-content">
      <view v-for="user in onlineList" :key="user.tokenId" class="list-item" @click="handleView(user)">
        <view class="list-avatar">
          <uni-icons type="person-filled" size="24" color="#52c41a"></uni-icons>
        </view>
        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ user.userName }}</text>
            <text class="list-subtitle">{{ user.loginLocation || '未知位置' }} •
              在线{{ getOnlineDuration(user.loginTime) }}
            </text>
            <view class="status-badge status-normal">在线</view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="location" size="14" color="#999"/>
              <text class="detail-text">{{ user.ipaddr }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="search" size="14" color="#999"/>
              <text class="detail-text">{{ user.browser || '未知' }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="calendar" size="14" color="#999"/>
              <text class="detail-text">{{ parseTime(user.loginTime, '{y}-{m}-{d} {h}:{i}') }}</text>
            </view>
            <view class="detail-item" v-if="user.tokenId">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">Token: {{ user.tokenId.substring(0, 8) }}...</text>
            </view>
          </view>
        </view>
        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleView(user)">
            <uni-icons type="eye" size="14" color="#007aff"/>
            <text class="action-text">详情</text>
          </view>
          <view class="action-btn action-default" @click.stop="handleCopy(user.tokenId)">
            <uni-icons type="paperplane" size="14" color="#666"/>
            <text class="action-text">复制</text>
          </view>
          <view v-if="!isCurrentUser(user)" class="action-btn action-danger" @click.stop="handleForceLogout(user)">
            <uni-icons type="close" size="14" color="#ff3b30"/>
            <text class="action-text">强退</text>
          </view>
          <view v-else class="current-user-badge">
            <text class="current-user-text">当前用户</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="onlineList.length > 0" class="list-load-more">
      <uni-load-more :status="loadStatus" :content-text="loadText" @clickLoadMore="handleLoadMore"/>
    </view>

    <view v-if="!loading && onlineList.length === 0" class="list-empty">
      <uni-icons type="person" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无在线用户</text>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {forceLogout, list} from '@/api/monitor/online'
import {parseTime} from '@/utils/ruoyi'
import {useUserStore} from '@/store/modules/user'

const {proxy} = getCurrentInstance()
const userStore = useUserStore()

// 数据定义
const onlineList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')
const filterPopup = ref(null)
let searchTimer = null

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ipaddr: '',
  userName: ''
})

/** 判断是否为当前用户 */
function isCurrentUser(user) {
  return user.tokenId === userStore.token
}


// 页面加载
onMounted(() => {
  getList()
})

// 获取在线用户列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await list(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        onlineList.value = newData
      } else {
        onlineList.value.push(...newData)
      }

      total.value = response.total || 0

      if (onlineList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取在线用户列表失败:', error)
    proxy.$modal.showToast('获取在线用户列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 筛选相关函数
function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter();
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {pageNum: 1, pageSize: 10, userName: '', ipaddr: ''})
}

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.userName = '';
  handleQuery()
}

// 计算在线时长
function getOnlineDuration(loginTime) {
  if (!loginTime) return '未知'

  const now = new Date()
  const login = new Date(loginTime)
  const diff = now - login

  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))

  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}


function handleLoadMore() {
  if (loadStatus.value === 'more') {
    queryParams.pageNum++
    getList()
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  onlineList.value = []
  getList()
}

// 业务操作方法
function handleView(user) {
  uni.navigateTo({
    url: `./detail?tokenId=${user.tokenId}`
  })
}

async function handleForceLogout(user) {
  try {
    await proxy.$modal.confirm(`确认要强退用户"${user.userName}"吗？`)

    const response = await forceLogout(user.tokenId)
    if (response.code === 200) {
      proxy.$modal.showToast('强退成功')
      handleQuery()
    }
  } catch (error) {
    console.error('强退用户失败:', error)
  }
}

function handleCopy(tokenId) {
  uni.setClipboardData({
    data: tokenId,
    success: () => {
      proxy.$modal.showToast('Token已复制到剪贴板')
    },
    fail: () => {
      proxy.$modal.showToast('复制失败')
    }
  })
}

function handleRefresh() {
  handleQuery()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';

.current-user-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  background-color: #f0f9ff;
  border: 1px solid #67c23a;
  border-radius: 4px;

  .current-user-text {
    color: #67c23a;
    font-size: 12px;
    font-weight: 500;
  }
}
</style>